package com.cooba.news_frament;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.cooba.R;
import com.cooba.activitys.NewsDetailsActivity;
import com.cooba.bean.NewsLoad;
import com.cooba.pullTorefresh.PullToRefreshBase;
import com.cooba.pullTorefresh.PullToRefreshListView;
import com.cooba.utils.CommonUtil;
import com.cooba.utils.ServerURL;
import com.cooba.utils.SharedPreferencesUtil;
import com.cooba.viewpager.ViewPageAdapter;
import com.google.gson.Gson;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2015/12/24.
 * 热点
 */
public class HotpointFrament extends Fragment implements View.OnClickListener, ViewPager.OnPageChangeListener {

    private View view;
    private PullToRefreshListView rListView;
    private HttpUtils httpUtils;
    private RequestParams params;
    private ViewPager viewpager;
    private List<NewsLoad.NewsListEntity> list = new ArrayList<>();
    // 底部小点的图片
    private ImageView[] points;
    // 引导图片资源
    private static final int[] pics = {R.drawable.head1, R.drawable.head2,
            R.drawable.head3};

    // 记录当前选中位置
    private int currentIndex;
    private TextView tv_refreshFlag;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            tv_refreshFlag.setVisibility(View.GONE);
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        try {
            if (view == null) {
                view = initview(inflater);
            }
            return view;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    private View initview(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.base_frament, null, false);
        initPullTorefresh(view);
        return view;
    }


    private void initPullTorefresh(View view) {
        tv_refreshFlag = (TextView) view.findViewById(R.id.test);
        rListView = (PullToRefreshListView) view.findViewById(R.id.lv_news);
        // initData();
        getData("0", true);
        rListView.setPullLoadEnabled(true);  //上拉加载，屏蔽
        rListView.setPullRefreshEnabled(true);
        rListView.setScrollLoadEnabled(true); //设置滚动加载可用
        rListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {//下拉刷新
                getData("0", false);
                String stringDate = CommonUtil.getStringDate();
                rListView.setLastUpdatedLabel(stringDate);

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {//上拉加载
                if (CommonUtil.isNetWork(getActivity())) {
                    getDataUp("1", true);
                } else {
                    Toast.makeText(getActivity(), "网络错误", Toast.LENGTH_SHORT).show();
                }
            }
        });
        rListView.getRefreshableView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String replyid = mAdapter.getList().get(position - 1).id;
                String title = mAdapter.getList().get(position - 1).title;
                Intent intent = new Intent(getActivity(), NewsDetailsActivity.class);
                intent.putExtra("newsDetialreplyid", replyid);
                intent.putExtra("newsDetialtitle", title);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.zcdh_set_in, R.anim.zcdh_alpha_out);
            }
        });
    }

    private void initData() {
        String result = SharedPreferencesUtil.getData(getActivity(), "hotpiont", "");
        if (!TextUtils.isEmpty(result)) {//如果缓存有数据,直接Gson解析
            paserData(result, false);
        }
        getData("0", true);
    }



    private void getDataUp(String next_key, final boolean isRefresh) {
        httpUtils = new HttpUtils();
        params = new RequestParams();
        params.addBodyParameter("dir_name", "inland");
        params.addBodyParameter("max_id", "20");
        params.addBodyParameter("limit_num", "10");
        httpUtils.send(HttpRequest.HttpMethod.POST, ServerURL.httpUrl + ServerURL.newsList, params, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
                Log.e("sss", "获取失败");
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                paserData(responseInfo.result, isRefresh);
            }
        });
    }

    private void getData(String next_key, final boolean isRefresh) {
        httpUtils = new HttpUtils();
        params = new RequestParams();
        params.addBodyParameter("dir_name", "inland");
        params.addBodyParameter("first_flag", "0");
        params.addBodyParameter("page_size", "10");
        httpUtils.send(HttpRequest.HttpMethod.POST, ServerURL.httpUrl + ServerURL.newsList, params, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
                Log.e("sss", "获取失败");
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                paserData(responseInfo.result, isRefresh);
                Log.e("ttttt", "获取失败" + responseInfo.result);
            }
        });
    }

    private NewsAdapter mAdapter;

    private void paserData(String result, boolean isRefresh) {
        SharedPreferencesUtil.saveData(getActivity(), "hotpiont", result);
        if (!isRefresh) {
            list.clear();
        }
        NewsLoad shitingBean = new Gson().fromJson(result, NewsLoad.class);
        if (mAdapter == null) {
            mAdapter = new NewsAdapter(getContext(), shitingBean.newsList);
            rListView.getRefreshableView().setAdapter(mAdapter);
            initHeadView();
        } else {
            list.addAll(shitingBean.newsList);
            mAdapter.setList(list);
        }
        tv_refreshFlag.setText("酷吧为您推荐10条更新");
        tv_refreshFlag.setVisibility(View.VISIBLE);
        Message message = handler.obtainMessage();
        handler.sendMessageDelayed(message, 2000);
        rListView.onPullDownRefreshComplete();
        rListView.onPullUpRefreshComplete();
    }

    class NewsAdapter extends BaseAdapter {
        private Context context;
        private List<NewsLoad.NewsListEntity> list;

        public List<NewsLoad.NewsListEntity> getList() {
            return list;
        }

        public void setList(List<NewsLoad.NewsListEntity> list) {
            this.list = list;
            notifyDataSetChanged();
        }

        public NewsAdapter(Context context, List<NewsLoad.NewsListEntity> list) {
            this.context = context;
            this.list = list;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder holder = null;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = LayoutInflater.from(context).inflate(R.layout.news_list_item, parent, false);
                holder.title = (TextView) convertView.findViewById(R.id.tv1);
                holder.description = (TextView) convertView.findViewById(R.id.tv2);
                holder.img = (ImageView) convertView.findViewById(R.id.iv);
                convertView.setTag(holder);

            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            if (list.get(position).title != null) {
                holder.title.setText(list.get(position).title.toString().replaceAll("\\\\", ""));//标题
            }
            if (list.get(position).description!=null) {
                holder.description.setText(list.get(position).description.toString().replaceAll("\\\\", ""));//描述
            }
            //图片
            BitmapUtils bitmapUtils = new BitmapUtils(context);
            String cover = list.get(position).img_url;

            bitmapUtils.display(holder.img, cover);
            return convertView;
        }

        class ViewHolder {
            public TextView title;
            public TextView description;
            public ImageView img;

        }
    }

    private void initHeadView() {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.news_head_viewpager, null);
        viewpager = (ViewPager) view.findViewById(R.id.headviewpager);
        List<ImageView> listtemp = new ArrayList<ImageView>();

        // 定义一个布局并设置参数
        LinearLayout.LayoutParams mParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT);

        // 初始化引导图片列表
        for (int i = 0; i < pics.length; i++) {
            ImageView iv = new ImageView(getContext());
            iv.setLayoutParams(mParams);
            //防止图片不能填满屏幕
            //  iv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,100));
            iv.setScaleType(ImageView.ScaleType.FIT_XY);
            //加载图片资源
            iv.setImageResource(pics[i]);
            listtemp.add(iv);
        }

        ViewPageAdapter viewadapter = new ViewPageAdapter(listtemp);
        rListView.getRefreshableView().addHeaderView(view);
        viewpager.setAdapter(viewadapter);
        viewpager.setOnPageChangeListener(this);
        initPoint(view);
    }

    /**
     * 初始化底部小点
     */
    private void initPoint(View view) {
        // View view = LayoutInflater.from(getContext()).inflate(R.layout.news_head_viewpager, null);
        LinearLayout linearLayout = (LinearLayout) view.findViewById(R.id.ll);
        points = new ImageView[pics.length];

        // 循环取得小点图片
        for (int i = 0; i < pics.length; i++) {
            // 得到一个LinearLayout下面的每一个子元素
            points[i] = (ImageView) linearLayout.getChildAt(i);
            // 默认都设为灰色
            points[i].setEnabled(true);
            // 给每个小点设置监听
            points[i].setOnClickListener(this);
            // 设置位置tag，方便取出与当前位置对应
            points[i].setTag(i);
        }

        // 设置当面默认的位置
        currentIndex = 0;
        // 设置为白色，即选中状态
        points[currentIndex].setEnabled(false);
    }

    @Override
    public void onClick(View v) {
        int position = (Integer) v.getTag();
        setCurView(position);
        setCurDot(position);
    }

    /**
     * 设置当前页面的位置
     */
    private void setCurView(int position) {
        if (position < 0 || position >= pics.length) {
            return;
        }
        viewpager.setCurrentItem(position);
    }

    /**
     * 设置当前的小点的位置
     */

    private void setCurDot(int positon) {
        if (positon < 0 || positon > pics.length - 1 || currentIndex == positon) {
            return;
        }
        points[positon].setEnabled(false);
        points[currentIndex].setEnabled(true);
        currentIndex = positon;
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        setCurDot(position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}